﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.XPath;

namespace KwaiXiaoDian.OpenApi.Swagger
{
    public class SwaggerOperationFilter : IOperationFilter
    {
        private readonly XPathNavigator _xmlNavigator;

        public SwaggerOperationFilter(XPathDocument xmlDoc)
        {
            _xmlNavigator = xmlDoc.CreateNavigator();
        }

        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var actionDescriptor = context?.ApiDescription?.ActionDescriptor as ControllerActionDescriptor;
            if (actionDescriptor != null)
            {
                ApplyControllerTags(operation, actionDescriptor.ControllerTypeInfo);
            }
        }

        /// <summary>
        /// 修改 TagName
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="controllerType"></param>
        private void ApplyControllerTags(OpenApiOperation operation, Type controllerType)
        {
            var controllerFullName = controllerType.FullName;
            var controllerNode = _xmlNavigator.SelectSingleNode("/doc/members/member[@name='T:" + controllerFullName + "']");
            if (controllerNode != null)
            {
                XPathNavigator summaryNode = controllerNode.SelectSingleNode("summary");
                if (summaryNode != null)
                {
                    foreach (var item in operation.Tags)
                    {
                        item.Name = $"{XmlCommentsTextHelper.Humanize(summaryNode.InnerXml)} ({item.Name})" ;
                    }
                }
            }
        }
    }
}
